package tksDB

import (
	"database/sql"
	"fmt"
	"github.com/astaxie/beedb"
	_ "github.com/go-sql-driver/mysql"
)

type TksDB struct {
	sql *sql.DB
	orm beedb.Model
}

func InitMysql(user string, pwd string, host string, port int, dbs string, charset string) *TksDB {
	db := new(TksDB)
	var connInfo string
	var err error
	connInfo = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", user, pwd, host, port, dbs, charset)
	db.sql, err = sql.Open("mysql", connInfo)
	if err != nil {
		panic(err.Error())
	}
	db.orm = beedb.New(db.sql)
	return db
}

func (db *TksDB) GetAllDataFromMysql(u interface{}) error {
	return db.orm.FindAll(u)
}

func (db *TksDB) GetDataFromMysql(cond string, v interface{}, u interface{}) error {
	return db.orm.Where(cond, v).Find(u)
}

func (db *TksDB) SetDataIntoMysql(u interface{}) error {
	return db.orm.Save(u)
}

func (db *TksDB) Close() {
	db.sql.Close()
}
